package com.atguigu.gmall.scheduled.handler;

import com.atguigu.gmall.scheduled.mapper.CartMapper;
import com.atguigu.gmall.scheduled.pojo.Cart;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.google.gson.Gson;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import javafx.beans.binding.When;
import jdk.nashorn.internal.ir.WhileNode;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;


import java.util.List;

import static org.springframework.data.repository.init.ResourceReader.Type.JSON;

@Component
public class CartJobHandler {
    @Autowired
    StringRedisTemplate redisTemplate;
    private  final static String KEY = "cart:async:exception";

    private final static String KEY_PREFIX = "cart:info:";
    @Autowired
    CartMapper cartMapper;
    //定时任务,查询redis中的userId，并将对应的数据同步到mysql数据库中
    @XxlJob("cartJobHandler")
    public ReturnT<String> executor(String param){
        BoundSetOperations<String, String> setOps = redisTemplate.boundSetOps(KEY);

        String userId = setOps.pop();
        while (StringUtils.isNotBlank(userId)){
            //先删除mysql中对应的userId的信息
            this.cartMapper.delete(new UpdateWrapper<Cart>().eq("user_id",userId));

            //查询redis中对应的数据
            BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(KEY_PREFIX + userId);
            List<Object> CartJson = hashOps.values();
            if (CollectionUtils.isEmpty(CartJson)){
                continue;
            }
            //如果redis中有数据，将数据保存到mysql数据库
            CartJson.forEach(cart->{
                Gson gson = new Gson();
                Cart cart1 = gson.fromJson(cart.toString(), Cart.class);
                this.cartMapper.insert(cart1);
            });
           userId = setOps.pop();

        }
        return ReturnT.SUCCESS;
    }
}
